package com.just.school_campus.service.impl;

import com.just.school_campus.dao.GoodsMapper;
import com.just.school_campus.model.Goods;
import com.just.school_campus.model.GoodsExample;
import com.just.school_campus.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsMapper goodsDao;

    @Override
    public String getRandomGoodsId(){
        synchronized (this){
            while (true){
                String goodsId = UUID.randomUUID().toString();
                //判断是否存在 ID 重复
                GoodsExample example = new GoodsExample();
                example.createCriteria().andGoodsIdEqualTo(goodsId);
                if(goodsDao.selectByExample(example).size() == 0){
                    return goodsId;
                }
            }
        }
    }

    @Override
    public int createGoods(Goods goods) {
        //新商品默认热度为0，上架状态为1，可用状态为1
        return goodsDao.insertSelective(goods);
    }

    @Override
    public List<Goods> getMyGoods(String userId) {
        GoodsExample example = new GoodsExample();
        example.createCriteria().andUserIdEqualTo(userId);
        List<Goods> goods = goodsDao.selectByExample(example);
        return goods;
    }

    @Override
    public Goods getGoodsDscrip(String goodsId) {
        return goodsDao.selectByPrimaryKey(goodsId);
    }

    @Override
    public int saveGoodsDscrip(Goods goods) {
        GoodsExample example = new GoodsExample();
        example.createCriteria().andGoodsIdEqualTo(goods.getGoodsId());
        return goodsDao.updateByExample(goods, example);
    }

    @Override
    public int deleteMyGoods(String goodsId) {
        return goodsDao.deleteByPrimaryKey(goodsId);
    }

    @Override
    public Goods getGoodsById(String goodsId) {
        GoodsExample example = new GoodsExample();
        example.createCriteria().andGoodsIdEqualTo(goodsId)
                .andUpStatusEqualTo(1)
                .andUseStatusEqualTo(1);
        return goodsDao.selectByExample(example).get(0);
    }

    @Override
    public List<Goods> getIndexGoods(int index) {
        List<Goods> list = null;
        //获取热门精品
        if(index == 1){
            list = goodsDao.findAllSortListByHot();
        }else if(index == 2){
            //获取低价好物
            list = goodsDao.findAllSortListByPrice();
        }else{
            //获取 9 新以上
            list = goodsDao.findAllSortListByLevel(90);
        }
        return list;
    }

    @Override
    public List<Goods> getSearchGoods(String text) {
        GoodsExample example = new GoodsExample();
        example.createCriteria().andNameLike(text)
                .andUpStatusEqualTo(1)
                .andUseStatusEqualTo(1);
        return goodsDao.selectByExample(example);
    }
}
